import config from '@/utils/config';
import md5 from 'js-md5';
export function pre_md5(str) {
	let string = typeof str == 'object' ? convertObj(str) : str;
    let prestr = string.indexOf("?")!=-1 ? `${string}?key=${config.MD5_KEY}` : `${string}&key=${config.MD5_KEY}`;
    let sign = md5(prestr);
    // console.log("-- SIGN -- \n",prestr, `\n sign: ${sign}`)
    return sign;
}

// 参数排序
var sortObject = function (obj){
    //排序之后去掉值为undefined
    let newSort= {};
    let keysSorted = Object.keys(obj).sort();
    for( let i=0 ;i < keysSorted.length ;i++ ){
      if(obj[keysSorted[i]] || keysSorted[i] == 'images')
      newSort[keysSorted[i]] = obj[keysSorted[i]];
    }
    return newSort;
  }

// 参数拼接
 var convertObj = function (data) {
    var _result = [];
    data = sortObject(data);
    for (var key in data) {
      var value = data[key];
        if (Object.prototype.toString.call(value) == '[object Array]') {
          
            _result.push(key + "=" + JSON.stringify(value));
          
        } else {
          _result.push(key + '=' + value);
        }
      
    }
    return _result.join('&');
  }
